from math import radians, sin, cos, atan2
from random import uniform

from vectors import Vector

FULL_CIRCLE = radians(360)

def clamp_angle(angle):
	"""Return the angle normalised so: 0 <= angle < FULL_CIRCLE."""
	if angle < 0:
		return angle + FULL_CIRCLE
	elif angle >= FULL_CIRCLE:
		return angle - FULL_CIRCLE
	else:
		return angle


def direction_to_angle(angle, target_angle):
	"""Return the shortest direction to rotate in to reach target_angle from 
	angle."""
	clockwise, anticlockwise = rotations_to_angle(angle, target_angle)
			
	if clockwise < anticlockwise:
		return 1
	else:
		return -1

	
def rotations_to_angle(angle, target_angle):	
	"""Return the clockwise and anticlockwise angles from angle to 
	target_angle."""
	small_angle = min(angle, target_angle)
	large_angle = max(angle, target_angle)

	if angle > target_angle:
		anticlockwise = large_angle - small_angle		
		clockwise = FULL_CIRCLE - anticlockwise
	else:
		clockwise = large_angle - small_angle		
		anticlockwise = FULL_CIRCLE - clockwise
		
	return clockwise, anticlockwise


def angle_between_points(point, target_point):
	"""Return the angle between the horizontal and the line passing through
	point and target_point."""
	x, y = point
	target_x, target_y = target_point
	
	angle = atan2(target_y - y, target_x - x)
	
	return clamp_angle(angle)

	
def random_point_in_circle(circle):
	"""Return a random point inside the circle."""
	position, radius = circle
	x, y = position
	
	angle = uniform(0, FULL_CIRCLE)
	offset = uniform(0, radius)
	return (x + offset * cos(angle), y + offset * sin(angle))
